package com.zhang.apipassenger.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.zhang.internalcommon.constant.TokenConstants;
import com.zhang.internalcommon.dto.ResponseResult;
import com.zhang.internalcommon.dto.TokenResult;
import com.zhang.internalcommon.utils.JwtUtils;
import com.zhang.internalcommon.utils.RedisPrefixUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author ADMIN
 */
public class JwtInterceptor implements HandlerInterceptor {
	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		boolean result = true;
		String resultString = "";

		String token = request.getHeader("Authorization");
		TokenResult tokenResult = null;
		try {
			tokenResult = JwtUtils.parseToken(token);
		} catch (Exception e) {
			resultString = e.getMessage();
			result = false;
		}

		if (tokenResult == null) {
			resultString = "token invalid";
			result = false;
		} else {
			// 	拼接key
			String phone = tokenResult.getPhone();
			String identity = tokenResult.getIdentity();

			String tokenKey = RedisPrefixUtils.generateTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);
			// 从redis中取出token
			String tokenRedis = redisTemplate.opsForValue().get(tokenKey);
			if (StringUtils.isBlank(tokenRedis)) {
				resultString = "token invalid";
				result = false;
			}else{
				// 比较是否相等
				if (!token.trim().equals(tokenRedis.trim())){
					resultString = "token invalid";
					result = false;
				}
			}
		}

		if (!result) {
			PrintWriter out = response.getWriter();
			out.print(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
		}
		return result;
	}
}
